package com.ruoyi.task.dynamicSched.jdbc;

import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.util.List;

import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

// DAO
@Repository
@RequiredArgsConstructor
public class MysqlScheduleTaskDao {

    private static final Logger logger = LoggerFactory.getLogger(MysqlScheduleTaskDao.class);

    private final JdbcTemplate jdbcTemplate;

    private static final ResultSetExtractor<List<ScheduleTaskVo>> MULTI = r -> {
        List<ScheduleTaskVo> tasks = Lists.newArrayList();
        while (r.next()) {
            ScheduleTaskVo task = new ScheduleTaskVo();
            tasks.add(task);
            task.setId(r.getLong("id"));
            task.setCronExpression(r.getString("cron_expression"));
            task.setInitialDelayMilliseconds(r.getLong("initial_delay_milliseconds"));
            task.setIntervalMilliseconds(r.getLong("interval_milliseconds"));
            task.setTimeZone(r.getString("time_zone"));
            task.setTaskDescription(r.getString("task_description"));
            task.setTaskHostClass(r.getString("task_host_class"));
            task.setTaskMethod(r.getString("task_method"));
            task.setTaskType(r.getString("task_type"));
        }
        return tasks;
    };

    public List<ScheduleTaskVo> selectAllTasks() {
        String sql = "SELECT * FROM sched_schedule_task WHERE deleted = 0";
        logger.debug("sql: {}", sql);
        return jdbcTemplate.query(sql, MULTI);
    }
}
